// 数据结构示例
// 移除本地 bag/env 变量和模拟数据
// let bag = [
//     { id: 1, name: '生命药水', desc: '恢复50点生命值', qty: 5, type: '消耗品', rarity: 2, used: 12 },
//     { id: 2, name: '铁剑', desc: '基础近战武器', qty: 1, type: '武器', rarity: 1, used: 3 },
//     { id: 3, name: '魔法卷轴', desc: '释放火球术', qty: 2, type: '道具', rarity: 3, used: 1 },
// ];
// let env = [
//     { id: 101, name: '金币', desc: '可以用来购买物品', qty: 20, type: '货币', rarity: 1, used: 0 },
//     { id: 102, name: '木盾', desc: '基础防具', qty: 1, type: '防具', rarity: 1, used: 0 },
//     { id: 103, name: '稀有宝石', desc: '闪闪发光的宝石', qty: 1, type: '材料', rarity: 3, used: 0 },
// ];
// let nextId = 104;

// 适配重构后的HTML结构，更新DOM选择器
const bagList = document.getElementById('bag-list');
const envList = document.getElementById('env-list');
const highlightBtn = document.getElementById('highlight-btn');
const modal = document.getElementById('modal');
const closeModal = document.getElementById('close-modal');
const itemForm = document.getElementById('item-form');
const itemName = document.getElementById('item-name');
const itemDesc = document.getElementById('item-desc');
const itemQty = document.getElementById('item-qty');
const fightBtn = document.getElementById('fight-btn');
const shopBtn = document.getElementById('shop-btn');
const shopModal = document.getElementById('shop-modal');
const closeShopModal = document.getElementById('close-shop-modal');
const shopItemSelect = document.getElementById('shop-item-select');
const shopQtyInput = document.getElementById('shop-qty');
const shopBuyBtn = document.getElementById('shop-buy-btn');
const bagPrevBtn = document.getElementById('bag-prev');
const bagNextBtn = document.getElementById('bag-next');
const bagPageInfo = document.getElementById('bag-page-info');
const characterSelect = document.getElementById('character-select');

const EQUIP_DROPS = [
    { name: '青铜剑', desc: '基础武器，攻击+5', type: '武器', rarity: 1 },
    { name: '银盾', desc: '基础防具，防御+8', type: '防具', rarity: 2 },
    { name: '魔法项链', desc: '提升法力值', type: '饰品', rarity: 3 },
    { name: '治疗药水', desc: '恢复100点生命', type: '消耗品', rarity: 2 },
    { name: '火焰戒指', desc: '火焰抗性+10%', type: '饰品', rarity: 3 },
    { name: '黄金盔甲', desc: '稀有防具，防御+20', type: '防具', rarity: 4 },
    { name: '疾风靴', desc: '移动速度+10%', type: '鞋子', rarity: 2 },
    { name: '幸运币', desc: '据说能带来好运', type: '道具', rarity: 1 }
];

function randomDropEquip() {
    const drop = EQUIP_DROPS[Math.floor(Math.random() * EQUIP_DROPS.length)];
    // 检查周围物品区是否已有同名物品
    let exist = env.find(i => i.name === drop.name);
    if (exist) {
        exist.qty += 1;
    } else {
        env.push({
            id: nextId++,
            name: drop.name,
            desc: drop.desc,
            qty: 1,
            type: drop.type,
            rarity: drop.rarity,
            used: 0
        });
    }
    renderEnv();
    // 弹窗提示
    showFightResultModal(drop);
}

function showFightResultModal(drop) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'flex';
    modal.style.zIndex = 4000;
    modal.innerHTML = `<div class='modal-content' style='min-width:260px;text-align:center;'><h2 style='color:#22d3ee;'>打怪成功！</h2><p>你获得了：<br><strong style='color:#6366f1;font-size:1.2em;'>${drop.name}</strong></p><p style='color:#888;'>${drop.desc}</p><button id='close-fight-modal' style='margin-top:18px;background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;'>确定</button></div>`;
    document.body.appendChild(modal);
    document.getElementById('close-fight-modal').onclick = function () {
        document.body.removeChild(modal);
    };
}

fightBtn.onclick = randomDropEquip;

let editId = null;
let dragData = null;
let throwItemId = null;
let isBagDragging = false;
let bagPage = 1;
const BAG_PAGE_SIZE = 16;

// 背包格子固定为9x9
const BAG_SIZE = 81;
function getBagGrid() {
    // bagGrid: 长度81的数组，物品或null
    const grid = Array(BAG_SIZE).fill(null);
    bag.forEach((item, i) => {
        if (i < BAG_SIZE) grid[i] = item;
    });
    return grid;
}

const API_BASE = 'http://localhost:3001/api';
let currentCharacterId = null;

// 获取所有角色
async function fetchAllCharacters() {
    const res = await fetch(`${API_BASE}/characters`);
    return await res.json();
}

// 渲染角色选择下拉框
async function renderCharacterSelect() {
    const chars = await fetchAllCharacters();
    characterSelect.innerHTML = '';
    if (!chars.length) {
        alert('没有角色数据，请先创建角色！');
        return;
    }
    chars.forEach((c, idx) => {
        const opt = document.createElement('option');
        opt.value = c.id;
        opt.textContent = `${c.name}（Lv.${c.level}）`;
        characterSelect.appendChild(opt);
        // 页面首次加载时自动选中第一个角色
        if (currentCharacterId === null && idx === 0) {
            currentCharacterId = c.id;
        }
    });
    // 如果currentCharacterId无效，自动选第一个
    if (!chars.find(c => c.id == currentCharacterId)) {
        currentCharacterId = chars[0].id;
    }
    characterSelect.value = currentCharacterId;
}

// 获取装备栏数据
async function fetchEquipments() {
    console.log('fetchEquipments currentCharacterId:', currentCharacterId);
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/equipments`);
    const data = await res.json();
    console.log('equipments data:', data);
    return data;
}

// 渲染角色属性面板
async function renderCharacterAttributes() {
    const attrBox = document.getElementById('character-attributes');
    if (!attrBox) return;
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/attributes`);
    if (!res.ok) { attrBox.innerHTML = '<span style="color:#f00;">属性获取失败</span>'; return; }
    const { base, equip_bonus, final } = await res.json();
    attrBox.innerHTML = `
      <div class='attr-row'><span class='attr-label'>生命</span> <span class='attr-base'>${base.hp}</span> <span class='attr-bonus'>+${equip_bonus.hp}</span> <span class='attr-final'>${final.hp}</span></div>
      <div class='attr-row'><span class='attr-label'>攻击</span> <span class='attr-base'>${base.atk}</span> <span class='attr-bonus'>+${equip_bonus.atk}</span> <span class='attr-final'>${final.atk}</span></div>
      <div class='attr-row'><span class='attr-label'>防御</span> <span class='attr-base'>${base.def}</span> <span class='attr-bonus'>+${equip_bonus.def}</span> <span class='attr-final'>${final.def}</span></div>
      <div class='attr-row'><span class='attr-label'>法力</span> <span class='attr-base'>${base.mp}</span> <span class='attr-bonus'>+0</span> <span class='attr-final'>${final.mp}</span></div>
    `;
    // 高亮变化
    attrBox.classList.add('highlight');
    setTimeout(() => attrBox.classList.remove('highlight'), 600);
}
// 修改装备栏渲染，支持属性显示
async function renderEquipments() {
    const equipData = await fetchEquipments();
    const equipBox = document.getElementById('equipments');
    equipBox.innerHTML = '';
    const slotNames = {
        weapon: '武器',
        armor: '防具',
        accessory: '饰品',
        shoes: '鞋子'
    };
    equipData.forEach(equip => {
        const div = document.createElement('div');
        div.className = 'equip-slot' + (equip.item_id ? '' : ' empty');
        div.dataset.slot = equip.slot;
        div.setAttribute('droppable', 'true');
        // 拖拽到装备栏穿戴
        div.ondragover = function (e) { e.preventDefault(); div.classList.add('dragover'); };
        div.ondragleave = function () { div.classList.remove('dragover'); };
        div.ondrop = async function (e) {
            e.preventDefault(); div.classList.remove('dragover');
            if (!dragData || dragData.from !== 'bag') return;
            // 只允许装备类物品
            const bagData = await fetchBag();
            const item = bagData.find(i => i.item_id == dragData.id);
            if (!item || !['武器', '防具', '饰品', '鞋子'].includes(item.type)) return;
            // 槽位类型校验
            if ((div.dataset.slot === 'weapon' && item.type !== '武器') ||
                (div.dataset.slot === 'armor' && item.type !== '防具') ||
                (div.dataset.slot === 'accessory' && item.type !== '饰品') ||
                (div.dataset.slot === 'shoes' && item.type !== '鞋子')) {
                alert('装备类型与槽位不符！');
                return;
            }
            // 请求后端穿戴
            const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/equip`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ slot: div.dataset.slot, itemId: item.item_id })
            });
            if (!resp.ok) {
                const err = await resp.json().catch(() => ({}));
                alert('穿戴失败：' + (err.error || resp.status));
                return;
            }
            await renderBag();
            await renderEquipments();
            await renderCharacterAttributes();
        };
        // 点击卸下装备，弹出自定义弹窗
        div.onclick = async function () {
            if (!equip.item_id) return;
            showUnequipModal(equip.slot);
        };
        if (equip.item_id) {
            // 显示装备属性
            let attr = '';
            if (equip.attack_bonus && equip.attack_bonus !== 0) attr += `<span style='color:#f87171;'>攻+${equip.attack_bonus}</span> `;
            if (equip.defense_bonus && equip.defense_bonus !== 0) attr += `<span style='color:#60a5fa;'>防+${equip.defense_bonus}</span> `;
            if (equip.hp_bonus && equip.hp_bonus !== 0) attr += `<span style='color:#22d3ee;'>生+${equip.hp_bonus}</span> `;
            div.innerHTML = `<strong>${equip.name}</strong><br><span style='color:#888;font-size:0.98em;'>${slotNames[equip.slot]}</span><br><span style='color:#6366f1;'>稀有度:${equip.rarity}</span><br>${attr}`;
            div.classList.add('highlight');
            setTimeout(() => div.classList.remove('highlight'), 800);
        } else {
            div.innerHTML = `<span style='color:#bbb;'>${slotNames[equip.slot]}</span><br><span style='color:#ccc;'>空</span>`;
        }
        equipBox.appendChild(div);
    });
}
// 自定义美化卸下装备弹窗
window.showUnequipModal = function (slot) {
    const modal = document.getElementById('detail-modal');
    let body = modal.querySelector('.modal-content');
    if (!body) {
        modal.innerHTML = `<div class="modal-content" id="detail-modal-body"></div>`;
        body = modal.querySelector('.modal-content');
    }
    body.innerHTML = `
    <h2>卸下装备</h2>
    <p>确定要卸下该装备吗？</p>
    <div style='margin-top:18px;'>
      <button id='confirm-unequip-btn' style='background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;'>确定</button>
      <button id='cancel-unequip-btn' style='background:#f1f5f9;color:#333;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-left:12px;'>取消</button>
    </div>
    `;
    modal.style.display = 'flex';
    setTimeout(() => {
        document.getElementById('confirm-unequip-btn').onclick = async function () {
            await fetch(`${API_BASE}/characters/${currentCharacterId}/unequip`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ slot })
            });
            modal.style.display = 'none';
            await renderBag();
            await renderEquipments();
            await renderCharacterAttributes();
        };
        document.getElementById('cancel-unequip-btn').onclick = function () {
            modal.style.display = 'none';
        };
    }, 0);
};

// 渲染技能栏
async function renderSkills() {
    // 确保 skillTargetType 一定有定义
    window.skillTargetType = window.skillTargetType || {};
    // 动态统计怪物数量，供按钮禁用逻辑使用
    const monsters = await fetchMonsters();
    window._monsterCount = monsters.length;
    const skills = await fetchSkills();
    const skillBox = document.getElementById('skills-box');
    if (!skillBox) return;
    skillBox.innerHTML = '';
    if (!skills.length) {
        skillBox.innerHTML = '<span style="color:#bbb;">暂无已学技能</span>';
        return;
    }
    skills.forEach(skill => {
        try {
            console.log('[renderSkills] 渲染技能:', skill);
            const div = document.createElement('div');
            div.className = 'skill-item';
            let btnHtml = '';
            let btnDisabled = false;
            let btnTip = '';
            // 兼容 skill.id 为数字或字符串
            const idKey = String(skill.id);
            const targetType = window.skillTargetType[idKey] || 'self';
            if (skill.type === '主动') {
                if (targetType === 'monster') {
                    btnDisabled = false;
                    btnTip = '';
                    if (window._monsterCount === 0) {
                        btnDisabled = true;
                        btnTip = '（无怪物）';
                    }
                    btnHtml = `<button class='use-skill-btn' data-id='${skill.id}' style='margin-top:6px;background:${btnDisabled ? '#aaa' : '#22d3ee'};color:#fff;border:none;border-radius:8px;padding:4px 16px;font-size:0.98em;cursor:pointer;' ${btnDisabled ? 'disabled' : ''}>释放${btnTip}</button>`;
                } else {
                    btnHtml = `<button class='use-skill-btn' data-id='${skill.id}' style='margin-top:6px;background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:4px 16px;font-size:0.98em;cursor:pointer;'>释放</button>`;
                }
            }
            // 主动和被动技能都渲染技能名和描述
            div.innerHTML = `
                <strong style='color:#6366f1;'>${skill.name}</strong>
                <span style='color:#888;font-size:0.98em;'>（${skill.type}）</span><br>
                <span style='color:#555;font-size:0.98em;'>${skill.desc}</span><br>
                ${btnHtml}
            `;
            // 技能详情弹窗
            div.onclick = function (e) {
                if (e.target.classList.contains('use-skill-btn')) return;
                alert(`技能：${skill.name}\n类型：${skill.type}\n消耗：${skill.mp_cost || 0}MP\n效果：${skill.desc}`);
            };
            skillBox.appendChild(div);
        } catch (err) {
            console.error('[renderSkills] 渲染技能出错:', skill, err);
        }
    });
    // 绑定主动技能释放
    skillBox.querySelectorAll('.use-skill-btn').forEach(btn => {
        if (btn.disabled) return;
        btn.onclick = async function (e) {
            e.stopPropagation();
            const skillId = Number(btn.dataset.id);
            const idKey = String(skillId);
            const targetType = window.skillTargetType[idKey] || 'self';
            let target = targetType;
            let monsterId = undefined;
            if (targetType === 'monster') {
                const monsters = await fetchMonsters();
                if (!monsters.length) return alert('没有怪物可用');
                monsterId = monsters[0].id;
            }
            const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/use-skill`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ skillId, monsterId, target })
            });
            if (!resp.ok) {
                const err = await resp.json().catch(() => ({}));
                alert('技能释放失败：' + (err.error || resp.status));
                return;
            }
            const data = await resp.json();
            if (targetType === 'monster') {
                alert(`技能释放成功！\n${data.result.skillName} 对 ${data.result.monsterName} 造成 ${data.result.damage || 0} 点伤害`);
            } else if (targetType === 'self') {
                alert(`技能释放成功！\n${data.result.skillName} 恢复自身 ${data.result.heal || 0} 点生命`);
            } else if (targetType === 'all') {
                alert(`技能释放成功！\n${data.result.skillName} 群体治疗：\n` + (data.result.healed || []).map(h => `${h.name}+${h.heal}`).join('，'));
            }
            await renderCharacterStatus();
            await renderMonsterInfo();
        };
    });
    // 渲染后输出skills-box内容
    console.log('[renderSkills] skills-box.innerHTML:', skillBox.innerHTML);
}
// 渲染怪物
async function renderMonsters() {
    const monsters = await fetchMonsters();
    // TODO: 渲染到左侧怪物区
    console.log('怪物', monsters);
}

// 渲染怪物信息
async function renderMonsterInfo() {
    const monsterBox = document.getElementById('monster-info');
    if (!monsterBox) return;
    const monsters = await fetchMonsters();
    if (!monsters.length) { monsterBox.innerHTML = '<span style="color:#aaa;">暂无怪物</span>'; return; }
    // 只显示第一个怪物（可扩展为选中）
    const monster = monsters[0];
    monsterBox.innerHTML = `
      <div><strong>${monster.name}</strong></div>
      <div>生命：${monster.hp}</div>
      <div>攻击：${monster.atk}</div>
      <div>防御：${monster.def}</div>
      <div style='color:#888;font-size:0.96em;'>${monster.desc || ''}</div>
    `;
}
// 渲染人物状态
async function renderCharacterStatus() {
    const statusBox = document.getElementById('character-status');
    if (!statusBox) return;
    // 获取角色基础信息
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}`);
    if (!res.ok) { statusBox.innerHTML = '<span style="color:#f00;">获取失败</span>'; return; }
    const char = await res.json();
    // 经验条
    const expPercent = Math.min(100, Math.round((char.exp / (100 * char.level)) * 100));
    statusBox.innerHTML = `
      <div><strong>${char.name}</strong> <span style='color:#6366f1;'>Lv.${char.level}</span></div>
      <div>生命：<span style='color:#ef4444;'>${char.hp}</span></div>
      <div>法力：<span style='color:#22d3ee;'>${char.mp}</span></div>
      <div>金币：<span style='color:#f59e42;'>${char.coin || 0}</span></div>
      <div>经验：${char.exp} / ${100 * char.level}</div>
      <div class='exp-bar'><div class='exp-bar-inner' style='width:${expPercent}%;'></div></div>
    `;
}
// 修改打怪按钮逻辑，展示详细战斗结果
fightBtn.onclick = async function () {
    // 获取角色属性
    const attrRes = await fetch(`${API_BASE}/characters/${currentCharacterId}/attributes`);
    if (!attrRes.ok) return alert('角色属性获取失败');
    const { final } = await attrRes.json();
    // 获取怪物
    const monsters = await fetchMonsters();
    if (!monsters.length) return alert('没有怪物可打');
    const monster = monsters[0];
    // 直接发起打怪请求，不再前端判断攻击力
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/fight`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ monsterId: monster.id })
    });
    if (!res.ok) { alert('打怪失败'); return; }
    const data = await res.json();
    // 展示详细战斗结果
    let msg = `<h2 style='color:#22d3ee;'>打怪成功！</h2>`;
    msg += `<div style='margin:8px 0;'>获得经验：<span style='color:#6366f1;'>${data.expGain}</span></div>`;
    msg += `<div style='margin:8px 0;'>获得金币：<span style='color:#f59e42;'>${data.coinGain}</span></div>`;
    if (data.dropItems && data.dropItems.length) {
        msg += `<div style='margin:8px 0;'>掉落物品：<ul style='margin:0 0 0 18px;'>`;
        data.dropItems.forEach(item => {
            msg += `<li><span style='color:#6366f1;'>${item.name}</span> x${item.qty} <span style='color:#888;font-size:0.95em;'>(稀有度:${item.rarity})</span></li>`;
        });
        msg += `</ul></div>`;
    } else {
        msg += `<div style='margin:8px 0;'>无物品掉落</div>`;
    }
    msg += `<div style='margin:8px 0;'>受到伤害：<span style='color:#ef4444;'>-${monster.atk}</span>，剩余生命：<span style='color:#ef4444;'>${data.hp}</span></div>`;
    if (data.levelUp) msg += `<div style='color:#22d3ee;font-weight:bold;'>升级啦！当前等级：Lv.${data.newLevel}</div>`;
    if (data.isDead) msg += `<div style='color:#f00;font-weight:bold;'>你已阵亡，请及时补充生命！</div>`;
    // 弹窗展示
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'flex';
    modal.style.zIndex = 4000;
    modal.innerHTML = `<div class='modal-content' style='min-width:320px;text-align:center;'>${msg}<button id='close-fight-modal' style='margin-top:18px;background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;'>确定</button></div>`;
    document.body.appendChild(modal);
    document.getElementById('close-fight-modal').onclick = function () {
        document.body.removeChild(modal);
    };
    // 刷新数据
    await renderCharacterStatus();
    await renderMonsterInfo();
    await renderBag();
    await renderEnv();
    // 升级且有技能选择时弹窗
    if (data.levelUp && data.candidateSkills && data.candidateSkills.length) {
        skillOptionsDiv.innerHTML = data.candidateSkills.map(s => `
            <label style='display:block;margin-bottom:14px;text-align:left;padding:8px 12px;border:1.5px solid #e0e7ff;border-radius:8px;cursor:pointer;'>
                <input type='radio' name='skill-option' value='${s.id}' style='margin-right:10px;'>
                <strong style='color:#6366f1;'>${s.name}</strong> <span style='color:#888;font-size:0.98em;'>(${s.type})</span><br>
                <span style='color:#555;font-size:0.98em;'>${s.desc}</span>
            </label>
        `).join('');
        skillSelectModal.style.display = 'flex';
        // 可选：升级弹窗后自动关闭战斗结果弹窗
        document.getElementById('close-fight-modal') && document.getElementById('close-fight-modal').click();
        // 升级后刷新技能栏
        skillSelectCallback = async () => { await renderCharacterStatus(); };
    }
    // 打怪胜利后自动刷新怪物信息区
    if (data.win && data.newMonster) {
        // 更新怪物信息区
        const monsterBox = document.getElementById('monster-info');
        if (monsterBox) {
            monsterBox.innerHTML = `
              <div><strong style='color:${data.newMonster.isBoss ? '#f59e42' : '#6366f1'};'>${data.newMonster.name}${data.newMonster.isBoss ? ' <span style=\'color:#f00;font-weight:bold;\'>[BOSS]</span>' : ''}</strong></div>
              <div>生命：${data.newMonster.hp}</div>
              <div>攻击：${data.newMonster.atk}</div>
              <div>防御：${data.newMonster.def}</div>
              <div style='color:#888;font-size:0.96em;'>${data.newMonster.desc || ''}</div>
            `;
        }
    }
};
// 页面初始化、角色切换时联动刷新
async function init() {
    await renderCharacterSelect();
    await renderBag();
    await renderSkills();
    await renderMonsters();
    await renderEquipments();
    await renderCharacterAttributes();
    await renderEnv();
    await renderMonsterInfo();
    await renderCharacterStatus();
}
characterSelect.onchange = async function () {
    currentCharacterId = characterSelect.value;
    await renderBag();
    await renderSkills();
    await renderMonsters();
    await renderEquipments();
    await renderCharacterAttributes();
    await renderEnv();
    await renderMonsterInfo();
    await renderCharacterStatus();
};

// 修改API调用使用currentCharacterId
async function fetchBag() {
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/bag`);
    return await res.json();
}
async function fetchSkills() {
    console.log('fetchSkills currentCharacterId:', currentCharacterId);
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/skills`);
    const data = await res.json();
    console.log('skills data:', data);
    return data;
}
async function fetchMonsters() {
    const res = await fetch(`${API_BASE}/monsters`);
    return await res.json();
}
async function fetchCharacter() {
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}`);
    return await res.json();
}

// 补全 fetchEnv 函数，统一通过API获取当前角色周围物品
async function fetchEnv() {
    const res = await fetch(`${API_BASE}/characters/${currentCharacterId}/env`);
    if (!res.ok) throw new Error('获取周围物品失败');
    return await res.json();
}

// 统一详情弹窗显示函数
function showDetailModal(html, afterRender) {
    const modal = document.getElementById('detail-modal');
    modal.innerHTML = `<div class="modal-content">${html}</div>`;
    modal.style.display = 'flex';
    // 绑定关闭按钮
    const closeBtn = modal.querySelector('.close-detail-modal');
    if (closeBtn) closeBtn.onclick = window.hideBagDetailModal;
    if (typeof afterRender === 'function') afterRender(modal);
}

// 详情弹窗（背包物品/装备通用）
window.showBagDetailModal = function (item) {
    console.log('[showBagDetailModal] called, item:', item);
    const modal = document.getElementById('detail-modal');
    const body = modal.querySelector('.modal-content');
    if (!item) {
        alert('未找到该背包物品详情，可能已被丢弃或数据异常');
        return;
    }
    let canUse = ['消耗品', '道具'].includes(item.type);
    let canEquip = ['武器', '防具', '饰品', '鞋子'].includes(item.type);
    body.innerHTML = `
    <span class='close-detail-modal' style='position:absolute;right:18px;top:18px;font-size:1.5em;cursor:pointer;'>&times;</span>
    <h2>${item.name}</h2>
    <span class='qty'>x${item.qty}</span>
    <p>${item.desc}</p>
    <p>类型：<span class='type'>${item.type}</span></p>
    <p>稀有度：<span class='rarity'>${item.rarity}</span></p>
    <div style='margin-top:18px;'>
      <button id='detail-throw-btn' style='background:#f87171;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;'>抛弃</button>
      ${canUse ? `<button id='use-item-btn' style='background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-left:12px;'>使用</button>` : ''}
      ${canEquip ? `<button id='equip-item-btn' style='background:#6366f1;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-left:12px;'>装备</button>` : ''}
    </div>
    `;
    modal.style.display = 'flex';
    // 绑定事件
    body.querySelector('.close-detail-modal').onclick = window.hideBagDetailModal;
    body.querySelector('#detail-throw-btn').onclick = function () { window.hideBagDetailModal(); showThrowModal(item); };
    if (canUse) {
        body.querySelector('#use-item-btn').onclick = function () { showUseItemModal(item); };
    }
    if (canEquip) {
        body.querySelector('#equip-item-btn').onclick = async function () {
            let slot = '';
            if (item.type === '武器') slot = 'weapon';
            else if (item.type === '防具') slot = 'armor';
            else if (item.type === '饰品') slot = 'accessory';
            else if (item.type === '鞋子') slot = 'shoes';
            if (!slot) return alert('无法识别装备类型');
            const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/equip`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slot, itemId: item.item_id })
            });
            if (!resp.ok) {
                const err = await resp.json().catch(() => ({}));
                alert('装备失败：' + (err.error || resp.status));
                return;
            }
            modal.style.display = 'none';
            await renderBag(); await renderEquipments(); await renderCharacterAttributes();
        };
    }
};

// 详情弹窗（周围物品）
window.showEnvDetail = async function (envId) {
    console.log('[showEnvDetail] called, envId:', envId);
    const envData = await fetchEnv();
    console.log('[showEnvDetail] envData:', envData);
    const item = envData.find(i => String(i.env_id) === String(envId));
    console.log('[showEnvDetail] item:', item);
    if (!item) {
        alert('未找到该物品详情，可能已被拾取或数据异常');
        return;
    }
    const modal = document.getElementById('detail-modal');
    const body = modal.querySelector('.modal-content');
    body.innerHTML = `
    <span class='close-detail-modal' style='position:absolute;right:18px;top:18px;font-size:1.5em;cursor:pointer;'>&times;</span>
    <h2>${item.name}</h2>
    <span class='qty'>x${item.qty}</span>
    <p>${item.desc}</p>
    <p>类型：<span class='type'>${item.type}</span></p>
    <p>稀有度：<span class='rarity'>${item.rarity}</span></p>
    <button id='pickup-btn'>拾取</button>
    `;
    modal.style.display = 'flex';
    // 绑定事件
    body.querySelector('.close-detail-modal').onclick = window.hideBagDetailModal;
    body.querySelector('#pickup-btn').onclick = async function (e) {
        e.stopPropagation();
        await window.pickupItem(item.env_id);
        modal.style.display = 'none';
    };
};

// 渲染背包，点击物品弹详情
async function renderBag() {
    const bagData = await fetchBag();
    bagList.innerHTML = '';
    const totalPage = Math.max(1, Math.ceil(bagData.length / BAG_PAGE_SIZE));
    if (bagPage > totalPage) bagPage = totalPage;
    const start = (bagPage - 1) * BAG_PAGE_SIZE;
    const end = start + BAG_PAGE_SIZE;
    const pageItems = bagData.slice(start, end);
    for (let i = 0; i < BAG_PAGE_SIZE; i++) {
        const item = pageItems[i];
        const li = document.createElement('li');
        if (item) {
            li.setAttribute('draggable', 'true');
            li.dataset.id = item.item_id;
            li.dataset.from = 'bag';
            li.ondragstart = function (e) {
                dragData = { id: parseInt(li.dataset.id), from: li.dataset.from };
                li.classList.add('dragging');
                setTimeout(() => li.classList.remove('dragging'), 0);
                e.dataTransfer.effectAllowed = 'move';
            };
            li.ondragend = function () { dragData = null; };
            li.innerHTML = `<strong>${item.name}</strong><span class="qty">x${item.qty}</span>`;
            li.onclick = function () {
                console.log('[renderBag] li.onclick, item:', item);
                showBagDetailModal(item);
            };
        } else {
            li.classList.add('empty');
            li.innerHTML = '';
        }
        bagList.appendChild(li);
    }
    bagPrevBtn.disabled = bagPage === 1;
    bagNextBtn.disabled = bagPage === totalPage;
    bagPageInfo.textContent = `第${bagPage}页 / 共${totalPage}页`;
}

// 渲染装备栏，点击已装备物品弹详情
async function renderEquipments() {
    const equipData = await fetchEquipments();
    const equipBox = document.getElementById('equipments');
    equipBox.innerHTML = '';
    const slotNames = { weapon: '武器', armor: '防具', accessory: '饰品', shoes: '鞋子' };
    equipData.forEach(equip => {
        const div = document.createElement('div');
        div.className = 'equip-slot' + (equip.item_id ? '' : ' empty');
        div.dataset.slot = equip.slot;
        div.setAttribute('droppable', 'true');
        div.ondragover = function (e) { e.preventDefault(); div.classList.add('dragover'); };
        div.ondragleave = function () { div.classList.remove('dragover'); };
        div.ondrop = async function (e) {
            e.preventDefault(); div.classList.remove('dragover');
            if (!dragData || dragData.from !== 'bag') return;
            const bagData = await fetchBag();
            const item = bagData.find(i => i.item_id == dragData.id);
            if (!item || !['武器', '防具', '饰品', '鞋子'].includes(item.type)) return;
            if ((div.dataset.slot === 'weapon' && item.type !== '武器') ||
                (div.dataset.slot === 'armor' && item.type !== '防具') ||
                (div.dataset.slot === 'accessory' && item.type !== '饰品') ||
                (div.dataset.slot === 'shoes' && item.type !== '鞋子')) {
                alert('装备类型与槽位不符！');
                return;
            }
            const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/equip`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slot: div.dataset.slot, itemId: item.item_id })
            });
            if (!resp.ok) {
                const err = await resp.json().catch(() => ({}));
                alert('穿戴失败：' + (err.error || resp.status));
                return;
            }
            await renderBag(); await renderEquipments(); await renderCharacterAttributes();
        };
        // 点击已装备物品弹详情
        div.onclick = function () {
            if (equip.item_id) showBagDetailModal({ ...equip, item_id: equip.item_id, name: equip.name, desc: equip.desc, qty: 1, type: equip.type, rarity: equip.rarity });
        };
        if (equip.item_id) {
            let attr = '';
            if (equip.attack_bonus && equip.attack_bonus !== 0) attr += `<span style='color:#f87171;'>攻+${equip.attack_bonus}</span> `;
            if (equip.defense_bonus && equip.defense_bonus !== 0) attr += `<span style='color:#60a5fa;'>防+${equip.defense_bonus}</span> `;
            if (equip.hp_bonus && equip.hp_bonus !== 0) attr += `<span style='color:#22d3ee;'>生+${equip.hp_bonus}</span> `;
            div.innerHTML = `<strong>${equip.name}</strong><br><span style='color:#888;font-size:0.98em;'>${slotNames[equip.slot]}</span><br><span style='color:#6366f1;'>稀有度:${equip.rarity}</span><br>${attr}`;
            div.classList.add('highlight');
            setTimeout(() => div.classList.remove('highlight'), 800);
        } else {
            div.innerHTML = `<span style='color:#bbb;'>${slotNames[equip.slot]}</span><br><span style='color:#ccc;'>空</span>`;
        }
        equipBox.appendChild(div);
    });
}

// 渲染周围物品，点击li或详情按钮弹详情，拾取按钮只拾取
async function renderEnv() {
    const envData = await fetchEnv();
    envList.innerHTML = '';
    envData.forEach(item => {
        const li = document.createElement('li');
        li.setAttribute('draggable', 'true');
        li.dataset.id = item.env_id;
        li.dataset.from = 'env';
        li.ondragstart = function (e) {
            dragData = { id: parseInt(li.dataset.id), from: li.dataset.from };
            li.classList.add('dragging');
            setTimeout(() => li.classList.remove('dragging'), 0);
            e.dataTransfer.effectAllowed = 'move';
        };
        li.ondragend = function () { dragData = null; };
        li.innerHTML = `
      <strong>${item.name}</strong> <span style=\"color:#a3a3a3;font-size:0.9em;\">x${item.qty}</span><br>
      <span style=\"font-size:0.95em;\">${item.desc}</span><br>
      <span class=\"type-tag\">${item.type}</span><span class=\"rarity-tag\">| 稀有度:${item.rarity}</span>
      <div class=\"item-actions\">
        <button class='env-detail-btn'>详情</button>
        <button class='env-pickup-btn'>拾取</button>
      </div>
    `;
        li.onclick = function () {
            console.log('[renderEnv] li.onclick, item:', item);
            showEnvDetail(item.env_id);
        };
        const detailBtn = li.querySelector('.env-detail-btn');
        const pickupBtn = li.querySelector('.env-pickup-btn');
        if (detailBtn) {
            detailBtn.onclick = function (e) {
                e.stopPropagation();
                console.log('[renderEnv] detailBtn.onclick, item:', item);
                showEnvDetail(item.env_id);
            };
        }
        if (pickupBtn) {
            pickupBtn.onclick = function (e) { e.stopPropagation(); window.pickupItem(item.env_id); };
        }
        envList.appendChild(li);
    });
}

// 物品使用弹窗
window.showUseItemModal = function (item) {

    const modal = document.getElementById('detail-modal');
    let body = modal.querySelector('.modal-content');
    if (!body) {
        modal.innerHTML = `<div class="modal-content" id="detail-modal-body"></div>`;
        body = modal.querySelector('.modal-content');
    }
    body.innerHTML = `
    <h2>使用物品</h2>
    <p>${item.name}（${item.desc}）</p>
    <form id='use-item-form'>
      <label>数量：<input type='number' id='use-item-qty' min='1' max='${item.qty}' value='1' style='width:60px;padding:6px 8px;border-radius:6px;font-size:1em;'></label>
      <button type='submit' style='background:#22d3ee;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-left:18px;'>确定</button>
      <button type='button' id='cancel-use-item-btn' style='background:#f1f5f9;color:#333;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-left:12px;'>取消</button>
    </form>
    `;
    modal.style.display = 'flex';
    document.getElementById('use-item-form').onsubmit = async function (e) {
        e.preventDefault();
        const qty = parseInt(document.getElementById('use-item-qty').value) || 1;
        const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/use-item`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ itemId: item.item_id, qty })
        });
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({}));
            alert('使用失败：' + (err.error || resp.status));
            return;
        }
        const data = await resp.json();
        alert(data.effectMsg || '使用成功');
        modal.style.display = 'none';
        await renderBag();
        await renderCharacterStatus();
    };
    document.getElementById('cancel-use-item-btn').onclick = function () {
        modal.style.display = 'none';
    };
};

// 拾取周围物品
window.pickupItem = async function (envId) {
    await fetch(`${API_BASE}/characters/${currentCharacterId}/env/pick`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ envId })
    });
    await renderBag();
    await renderEnv();
};
// 丢弃物品到周围
function showThrowModal(item) {
    const throwModal = document.getElementById('throw-modal');
    let body = throwModal.querySelector('.modal-content');
    if (!body) {
        throwModal.innerHTML = `<div class="modal-content"><form id="throw-form"></form></div>`;
        body = throwModal.querySelector('.modal-content');
    }
    body.innerHTML = `
        <h2>抛弃物品</h2>
        <form id="throw-form">
            <div style="margin-bottom:12px;">
                <label id="throw-label" for="throw-qty">请输入要抛弃的数量（1-${item.qty}）：</label><br>
                <input type="number" id="throw-qty" min="1" max="${item.qty}" value="1" required style="width:100%;margin-top:6px;padding:8px 6px;font-size:1.1em;border-radius:6px;border:1px solid #ddd;">
            </div>
            <button type="submit" style="background:#06b6d4;color:#fff;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;margin-right:12px;">确定</button>
            <button type="button" id="cancel-throw-btn" style="background:#f1f5f9;color:#333;border:none;border-radius:8px;padding:8px 24px;font-size:1em;cursor:pointer;">取消</button>
        </form>
    `;
    throwModal.style.display = 'flex';
    document.getElementById('throw-form').onsubmit = async function (e) {
        e.preventDefault();
        const qty = parseInt(document.getElementById('throw-qty').value);
        await fetch(`${API_BASE}/characters/${currentCharacterId}/env/drop`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ itemId: item.item_id, qty })
        });
        throwModal.style.display = 'none';
        await renderBag();
        await renderEnv();
    };
    document.getElementById('cancel-throw-btn').onclick = function () {
        throwModal.style.display = 'none';
    };
}

// 拖拽交互
function addDropEvents(ul, type) {
    ul.ondragover = function (e) {
        e.preventDefault();
        ul.classList.add('dragover');
    };
    ul.ondragleave = function () {
        ul.classList.remove('dragover');
    };
    ul.ondrop = async function (e) {
        e.preventDefault();
        ul.classList.remove('dragover');
        if (!dragData) return;
        if (type === 'bag' && dragData.from === 'env') {
            // 拾取物品
            await window.pickupItem(dragData.id);
        } else if (type === 'env' && dragData.from === 'bag') {
            // 丢弃物品
            const bagData = await fetchBag();
            const item = bagData.find(i => i.item_id == dragData.id);
            if (item) showThrowModal(item);
        }
        dragData = null;
    };
}

// 智能整理（仅前端排序，不影响后端数据）
highlightBtn.onclick = async function () {
    const bagData = await fetchBag();
    bagData.sort((a, b) => {
        if (b.rarity !== a.rarity) return b.rarity - a.rarity;
        return a.type.localeCompare(b.type, 'zh-CN');
    });
    // 重新渲染排序后的数据
    bagList.innerHTML = '';
    const totalPage = Math.max(1, Math.ceil(bagData.length / BAG_PAGE_SIZE));
    if (bagPage > totalPage) bagPage = totalPage;
    const start = (bagPage - 1) * BAG_PAGE_SIZE;
    const end = start + BAG_PAGE_SIZE;
    const pageItems = bagData.slice(start, end);
    for (let i = 0; i < BAG_PAGE_SIZE; i++) {
        const item = pageItems[i];
        const li = document.createElement('li');
        if (item) {
            li.innerHTML = `<strong>${item.name}</strong><span class="qty">x${item.qty}</span>`;
            li.onclick = function (e) {
                showBagDetailModal(item);
                e.stopPropagation();
            };
        } else {
            li.classList.add('empty');
            li.innerHTML = '';
        }
        bagList.appendChild(li);
    }
    bagPrevBtn.disabled = bagPage === 1;
    bagNextBtn.disabled = bagPage === totalPage;
    bagPageInfo.textContent = `第${bagPage}页 / 共${totalPage}页`;
    highlightBtn.innerText = '已智能整理！';
    setTimeout(() => highlightBtn.innerText = '一键整理（智能推荐）', 1500);
};

// 分页按钮
bagPrevBtn.onclick = function () {
    if (bagPage > 1) {
        bagPage--;
        renderBag();
    }
};
bagNextBtn.onclick = async function () {
    const bagData = await fetchBag();
    const totalPage = Math.max(1, Math.ceil(bagData.length / BAG_PAGE_SIZE));
    if (bagPage < totalPage) {
        bagPage++;
        renderBag();
    }
};

addDropEvents(bagList, 'bag');
addDropEvents(envList, 'env');

// 不再需要 randomEnvBtn 相关逻辑

if (shopBtn) {
    shopBtn.onclick = async function () {
        shopModal.style.display = 'flex';
        // 加载所有物品
        const res = await fetch(`${API_BASE}/items`);
        const items = await res.json();
        shopItemSelect.innerHTML = '';
        items.forEach(item => {
            const price = item.price || (10 * (item.rarity || 1));
            const opt = document.createElement('option');
            opt.value = item.id;
            opt.textContent = `${item.name}（${price}金币/个，稀有度${item.rarity}）`;
            shopItemSelect.appendChild(opt);
        });
        shopQtyInput.value = 1;
    }
}
if (closeShopModal) closeShopModal.onclick = function () { shopModal.style.display = 'none'; };
if (shopBuyBtn) {
    shopBuyBtn.onclick = async function () {
        const itemId = shopItemSelect.value;
        const qty = parseInt(shopQtyInput.value) || 1;
        if (!itemId || qty < 1) return alert('请选择物品和数量');
        const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/shop/buy`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ itemId, qty })
        });
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({}));
            alert('购买失败：' + (err.error || resp.status));
            return;
        }
        const data = await resp.json();
        alert('购买成功！');
        shopModal.style.display = 'none';
        await renderCharacterStatus();
        await renderBag();
    }
}

const skillSelectModal = document.getElementById('skill-select-modal');
const closeSkillSelectModal = document.getElementById('close-skill-select-modal');
const skillOptionsDiv = document.getElementById('skill-options');
const skillSelectForm = document.getElementById('skill-select-form');

if (closeSkillSelectModal) closeSkillSelectModal.onclick = function () { skillSelectModal.style.display = 'none'; };

let skillSelectCallback = null;
if (skillSelectForm) {
    skillSelectForm.onsubmit = async function (e) {
        e.preventDefault();
        const checked = skillOptionsDiv.querySelector('input[name="skill-option"]:checked');
        if (!checked) return alert('请选择一个技能');
        const skillId = checked.value;
        // 调用后端学习技能
        const resp = await fetch(`${API_BASE}/characters/${currentCharacterId}/learn-skill`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ skillId })
        });
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({}));
            alert('学习技能失败：' + (err.error || resp.status));
            return;
        }
        alert('学习技能成功！');
        skillSelectModal.style.display = 'none';
        await renderSkills();
        if (typeof skillSelectCallback === 'function') skillSelectCallback();
    };
}

// 页面初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}

// 全局关闭详情弹窗方法
window.hideBagDetailModal = function () {
    const modal = document.getElementById('detail-modal');
    if (modal) modal.style.display = 'none';
};
// 遮罩层点击关闭（只允许点击遮罩层关闭，内容区点击不关闭）
const detailModal = document.getElementById('detail-modal');
if (detailModal) {
    detailModal.onclick = function (e) {
        if (e.target === detailModal) window.hideBagDetailModal();
    };
} 